package models

import (
	"gintest/database"
	"time"
)

//表结构
type Logistics struct {
	Id int `json:"id" gorm:"column:id;primary_key" form:"id"`
	Def  int `json:"def" gorm:"column:def" form:"def"`
	Title string `json:"title" gorm:"column:title" form:"title"`
	ShortTitle string `json:"short_title" gorm:"column:short_title" form:"short_title"`
	CreateAt time.Time  `json:"create_at" gorm:"column:create_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"create_at"`
	UpdateAt time.Time  `json:"update_at" gorm:"column:update_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"update_at"`
	DeleteAt time.Time  `json:"delete_at" gorm:"column:delete_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"delete_at"`
}
func (Logistics) TableName() string {
	return "logistics"
}

func GetLogisticsList(page uint64,pagesize uint64,keyword string)(data []Logistics,total uint64){
	var offset=(page-1)*pagesize
	db:=database.SqlDB.Model(Logistics{})
	if len(keyword)!=0{
		db=db.Where("title like ?","%"+keyword+"%")
	}

	db=db.Where("delete_at = 0 or delete_at is null")

	db.Offset(offset).Limit(pagesize).Order("id desc").Find(&data)

	db.Model(Ad{}).Count(&total)
	return data,total
}

func AddLogistics(data *Logistics) error{
	if data.UpdateAt.IsZero(){
		data.UpdateAt=time.Now()
	}
	if data.CreateAt.IsZero(){
		data.CreateAt=time.Now()
	}
	return database.SqlDB.Model(Logistics{}).Create(data).Error
}
func GetLogisticsById(id int) (data Logistics){
	database.SqlDB.Model(Logistics{}).Where("id=?",id).First(&data);
	return data
}
func EditLogisticsById(id int,data interface{}) error{
	//update_at不存在，填充当前时间
	if _, has := data.(map[string]interface{})["update_at"]; !has {
		data.(map[string]interface{})["update_at"]=time.Now()
	}
	return database.SqlDB.Model(&Logistics{}).Where("id=?",id).Updates(data).Error
}
func DelLogisticsByIds(ids []int) error{
	return database.SqlDB.Model(Logistics{}).Where("id in (?) and (delete_at = 0 or delete_at is null)",ids).Update("delete_at",time.Now().Local().String()).Error
}
func GetLogisticsCount()(total int){
	database.SqlDB.Table("logistics").Where("delete_at = 0 or delete_at is null").Count(&total)
	return
}